from django.views.generic.simple import direct_to_template
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from models import Options
from forms import OptionsForm

def show_options (request):
    '''shows current options or redirects to option configuration panel if none exist'''

    options = Options.objects.all ()
    if options is None or options.count() is 0:
        return show_options_form (request)

    return direct_to_template (request, 'options.html', { 'options': options[0] })

def show_options_form (request):
    ''' metoda do wprowadzania nowych danych konfiguracyjnych '''
    
    form = OptionsForm ()
    first_options_ever = True
            
    # jesli rekord opcji istnieje w bd - wypelnia forme
    options = Options.objects.all ()
    if options and options.count() != 0:
        form = OptionsForm (instance=options [0])
        first_options_ever = False
    
    return direct_to_template (request, 'form.html', { 'form': form, 'has_back': True, 'first_options_ever': first_options_ever, })

def check_options_form (request):
    """ metoda do sprawdzenia czy w formie nie ma bledow,
        zapisuje poprawna forme do bd
    """
    
    if request.method == 'POST':
        
        form = OptionsForm (request.POST)
        
        options = Options.objects.all ()
        if options and options.count() != 0:
            form = OptionsForm (request.POST, instance=options [0])

        if form.is_valid():
                    
            if 'submit' in request.POST:
                form.save(commit=True)
                
            return HttpResponseRedirect(reverse('opcje_konf'))
        
    return direct_to_template (request, 'form.html', { 'form': form, 'has_back': True })            

